package com.swpu.project.filter;

import cn.hutool.core.util.StrUtil;

import com.swpu.project.constant.RedisConstant;
import com.swpu.project.model.entity.LoginUser;
import com.swpu.project.util.JwtUtil;
import com.swpu.project.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends OncePerRequestFilter {
@Autowired
RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        if(StrUtil.isEmpty(token))
        {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        try {
            String id = JwtUtil.parseJWT(token).getSubject();
            String key= RedisConstant.USER_TOKEN_PREFIX +id;
            LoginUser loginUser = redisCache.getCacheObject(key);
            if(loginUser==null)
            {
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }
         //TODO  查询对应的权限信息传入authentication
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(httpServletRequest,httpServletResponse);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }



}
